<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { onMounted, reactive, ref } from 'vue';

import { ColPage } from '@vben/common-ui';

import { Button, List, ListItem, message, Tooltip } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { sysConfigPage, sysConfigRemove } from '#/api/sys/config';
import { getByDictType } from '#/api/sys/dict';
import { Icon } from '#/components/icon';
import { TableAction } from '#/components/table-action';

import DetailForm from './detail.vue';
import ConfigForm from './form.vue';
import { gridSchemas, searchFormSchemas } from './schemas';

const hasTopTableDropDownActions = ref(false);
const configFormRef = ref();
const detailFormRef = ref();
const formOptions: VbenFormProps = {
  ...searchFormSchemas,
  collapsed: true,
};

const gridOptions: VxeGridProps<any> = {
  ...gridSchemas,
  toolbarConfig: {
    ...gridSchemas.toolbarConfig,
    slots: {
      buttons: 'toolbar-buttons',
    },
    custom: {
      // 自定义列-图标
      icon: 'vxe-icon-menu',
    },
  },
  border: false,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await sysConfigPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          m_IN_groupCode: selectedGroupKey.value,
        });
      },
    },
  },
};
const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

// 打开新增表单
const handleAdd = () => {
  configFormRef.value.setData({
    isUpdate: false,
    gridApi,
  });
  configFormRef.value.open();
};
// 打开编辑表单
const handleEdit = (record: any) => {
  configFormRef.value.setData({
    record,
    isUpdate: true,
    gridApi,
  });
  configFormRef.value.open();
};
// 打开详情
const handleDetail = (record: any) => {
  detailFormRef.value.setData({
    record,
  });
  detailFormRef.value.open();
};
// 删除
const handleDelete = (row: any) => {
  let ids = [];
  if (row) {
    ids.push(row.id);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  sysConfigRemove({ ids }).then(() => {
    message.success('删除成功');
    gridApi.reload();
  });
};
const groupList = ref<Array<any>>([]);
const colPageProps = reactive({
  leftCollapsedWidth: 5,
  leftCollapsible: true,
  leftMaxWidth: 50,
  leftMinWidth: 20,
  leftWidth: 30,
  resizable: true,
  rightWidth: 70,
  splitHandle: true,
  splitLine: true,
});
const selectedGroupKey = ref<string[]>([]);
const handleGroupClick = (item: any) => {
  const index = selectedGroupKey.value.indexOf(item.value);
  if (index === -1) {
    // selectedGroupKey.value = [item.value]; // 单选模式
    selectedGroupKey.value = [...selectedGroupKey.value, item.value]; // 多选模式
  } else {
    selectedGroupKey.value.splice(index, 1); // 取消选中
  }
  gridApi.reload();
};
const colPageRef = ref();
onMounted(() => {
  getByDictType({ dictType: 'sys_config_group_code' }).then((res) => {
    if (res.length === 0) {
      // 等于0时，默认折叠
      colPageRef.value?.collapseLeft();
    }
    groupList.value = res;
  });
});
</script>

<template>
  <ColPage auto-content-height v-bind="colPageProps" ref="colPageRef">
    <template #left="{ isCollapsed, expand }">
      <div v-if="isCollapsed" @click="expand">
        <Tooltip title="点击展开左侧">
          <Button shape="circle" type="primary">
            <template #icon>
              <Icon class="text-2xl" icon="ant-design:arrow-right" />
            </template>
          </Button>
        </Tooltip>
      </div>
      <div
        v-else
        :style="{ minWidth: '200px' }"
        class="border-border bg-card mr-2 h-full overflow-auto rounded-[var(--radius)] border p-2"
      >
        <List class="h-full" size="small" bordered :data-source="groupList">
          <template #renderItem="{ item }">
            <ListItem
              :key="item.value"
              :class="{
                'bg-blue-100 text-blue-600': selectedGroupKey.includes(
                  item.value,
                ),
              }"
              @click="handleGroupClick(item)"
              class="cursor-pointer"
            >
              {{ item.label }}
            </ListItem>
          </template>
          <template #header>
            <div class="text-lg">配置分组</div>
          </template>
        </List>
      </div>
    </template>
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :actions="[
            {
              label: '新增',
              type: 'primary',
              icon: 'ant-design:plus-outlined',
              auth: ['admin', 'sys:config:save'],
              onClick: handleAdd.bind(null),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              auth: ['admin', 'sys:config:remove'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, false),
              },
            },
          ]"
        >
          <template #more>
            <Button style="margin-left: 8px">
              批量操作
              <Icon icon="ant-design:down-outlined" />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #toolbar-tools></template>
      <template #ACTION="{ row }">
        <TableAction
          :actions="[
            {
              label: '详情',
              type: 'link',
              size: 'small',
              auth: ['admin', 'sys:config:detail'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: '编辑',
              type: 'link',
              size: 'small',
              auth: ['admin', 'sys:config:update'],
              onClick: handleEdit.bind(null, row),
            },
          ]"
          :drop-down-actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              auth: ['admin', 'sys:config:remove'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
    <ConfigForm ref="configFormRef" />
    <DetailForm ref="detailFormRef" />
  </ColPage>
</template>
